import { Suspense, lazy } from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";

// 动态导入所有 `page.tsx` 文件
const pages = import.meta.glob("./pages/**/*/page.tsx");

// 将导入的组件转换为路由
const routes = Object.keys(pages).map((path) => {
  const component = lazy(
    pages[path] as () => Promise<{ default: React.ComponentType }>
  );
  const routePath = path
    .replace(/\.\/pages|page\.tsx$/g, "") // 去掉路径前缀和后缀
    .replace(/\[(.+)\]/, ":$1"); // 将 `[param]` 转换为 `:param`

  return {
    path: routePath === "/index" ? "/" : routePath, // 将 `/index` 转换为 `/`
    component,
  };
});

function App() {
  return (
    <Router>
      <Suspense fallback={<div>Loading...</div>}>
        <Routes>
          {routes.map(({ path, component: Component }) => (
            <Route key={path} path={path} element={<Component />} />
          ))}
        </Routes>
      </Suspense>
    </Router>
  );
}

export default App;
